#!/bin/bash
# (C) Copyright 2012,2013 Continuent, Inc - Released under the New BSD License
# Version 1.0.5 - 2013-04-03

cookbook_dir=$(dirname $0)

if [ ! -f $cookbook_dir/BOOTSTRAP.sh ]
then
    echo "$cookbook_dir/BOOTSTRAP.sh not found"
    exit 1
fi

. $cookbook_dir/BOOTSTRAP.sh NODES_MASTER_SLAVE.sh

are_you_sure_you_want_to_clear
if [ ! -f $MY_COOKBOOK_CNF ]
then
    write_my_cookbook_cnf
fi

# MYSQL="mysql -u $DATABASE_USER -p$DATABASE_PASSWORD -P $DATABASE_PORT"
for NODE in ${ALL_NODES[*]} 
do 
    if [ -f $cookbook_dir/data_loading ]
    then
        $cookbook_dir/load_data stop
    fi
    if [ "$STOP_REPLICATORS" == "1" ]
    then
        ssh $NODE "if [ -x $REPLICATOR ] ; then $REPLICATOR stop;  fi" 
    fi
    if [ "$REMOVE_TUNGSTEN_BASE" == "1" ]
    then
        ssh $NODE rm -rf $TUNGSTEN_BASE/*
    fi  
    if [ "$REMOVE_SERVICE_SCHEMA" == "1" ]
    then
        for D in $($MYSQL -h $NODE -BN -e 'show schemas like "tungsten%"' )
        do
            $MYSQL -h $NODE -e "drop schema $D"
        done
    fi
    if [ "$REMOVE_TEST_SCHEMAS" == "1" ]
    then
        $MYSQL -h $NODE -e 'drop schema if exists test'
        $MYSQL -h $NODE -e 'drop schema if exists evaluator'
    fi
    if [ "$REMOVE_DATABASE_CONTENTS" == "1" ]
    then
        for D in $($MYSQL -h $NODE -BN -e 'show schemas ' | grep -v -w 'mysql\|information_schema\|performance_schema'  )
        do
            $MYSQL -h $NODE -e "drop schema $D"
        done
    fi
    if [ "$CLEAN_NODE_DATABASE_SERVER" == "1" ]
    then
        $MYSQL -h $NODE -e 'create schema if not exists test'
        $MYSQL -h $NODE -e 'set global read_only=0'
        $MYSQL -h $NODE -e 'set global binlog_format=mixed'
        $MYSQL -h $NODE -e 'reset master'
    fi
done

for F in $INSTALL_LOG $CURRENT_TOPOLOGY $cookbook_dir/my.cookbook.cnf $cookbook_dir/db_use $cookbook_dir/current_install.summary
do
    [ -f $F ] && rm -f $F
done
